package com.zd.lwsq.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.zd.lwsq.domain.ApplicationInfo;
import com.zd.lwsq.service.ApplicationInfoService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

/**
 * 离乌申请数据Controller
 * 
 * @author fxiao
 * @date 2020-08-07
 */
@Controller
@RequestMapping("/lwsq/lwsq")
public class ApplicationInfoController extends BaseController
{
    private String prefix = "lwsq/lwsq";

    @Autowired
    private ApplicationInfoService applicationInfoService;

    @Autowired
    private SysDeptMapper deptMapper;

    @RequiresPermissions("lwsq:lwsq:view")
    @GetMapping()
    public String lwsq()
    {
        return prefix + "/lwsq";
    }


    /**
     * 查询离乌申请数据列表
     */
    @RequiresPermissions("lwsq:lwsq:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ApplicationInfo applicationInfo)
    {


        // 获取当前的用户信息,拿到部门id或者角色，过滤权限数据
        SysUser currentUser = ShiroUtils.getSysUser();
        SysDept dept = currentUser.getDept();

        String deptIds="";
        boolean isAdminAndShi=false;

        List<SysRole> roles = currentUser.getRoles();
        HashSet<Long> hset=new HashSet();
        for (SysRole r:roles  ) {
            if (r.getRoleId()==101 || r.getRoleId()==1){//市级-管理员
                deptIds+="";
                isAdminAndShi=true;
            }else if (r.getRoleId()==100){ //区级
                SysDept jdept = deptMapper.selectDeptById(currentUser.getDept().getParentId());
                long qdeptid=jdept.getParentId();
                List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(qdeptid);
                for (SysDept d:sysDepts) {
                   hset.add(d.getDeptId());
                }
                hset.add(qdeptid);
                applicationInfo.setBy8(String.valueOf(currentUser.getUserId()));
            }else if (r.getRoleId()==102){//街道办管理员
                List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(dept.getParentId());
                for (SysDept d:sysDepts) {
                    hset.add(d.getDeptId());
                }
                hset.add(dept.getParentId());
                applicationInfo.setBy8(String.valueOf(currentUser.getUserId()));
            }else if (r.getRoleId()==103){//社区管理员
                deptIds+=(dept.getDeptId()+",");
                hset.add(dept.getDeptId());

                applicationInfo.setBy8(String.valueOf(currentUser.getUserId()));
            }else {  //其他角色查不到数据
                hset.add(999l);
            }
        }

//查询权限范围内 某个社区，超出权限其他社区查不到
        Iterator<Long> iterator = hset.iterator();
        while (iterator.hasNext()){
            deptIds=deptIds+iterator.next()+",";
        }
        if( deptIds.endsWith(","))
            deptIds=deptIds.substring(0,deptIds.length()-1);

        if(null==applicationInfo.getSqCode()){
            if(isAdminAndShi){
                applicationInfo.setSqCode(null);
            }else{
                applicationInfo.setSqCode(String.valueOf(deptIds));
            }
        }else {
            if(!isAdminAndShi){
                String sqcode = applicationInfo.getSqCode();
                if (deptIds.indexOf(sqcode) >= 0) {
                    applicationInfo.setSqCode(sqcode);
                } else {
                    applicationInfo.setSqCode("999");
                }
            }
        }

        if(null!=applicationInfo.getJdbCode()||null !=applicationInfo.getQjCode()||null!=applicationInfo.getSqCode()){
            if(!isAdminAndShi){
                if(null!=applicationInfo.getQjCode()){
                    if(null!=applicationInfo.getJdbCode() && !applicationInfo.getJdbCode().equals("")){
                        if(null!=applicationInfo.getSqCode() && !applicationInfo.getSqCode().equals("")){
                            if(deptIds.indexOf(applicationInfo.getSqCode())<0){
                                applicationInfo.setSqCode("999");
                            }
                        }else{
                            if(deptIds.indexOf(applicationInfo.getJdbCode())<0){
                                applicationInfo.setSqCode("999");
                            }
                        }

                    }else {
                        if (deptIds.indexOf(applicationInfo.getQjCode()) < 0) {
                            applicationInfo.setQjCode("999");
                        }
                    }
                }
            }
        }

        startPage();
        List<ApplicationInfo> list = applicationInfoService.selectApplicationInfoList(applicationInfo);
        return getDataTable(list);
    }

    /**
     * 导出离乌申请数据列表
     */
    @RequiresPermissions("lwsq:lwsq:export")
    @Log(title = "离乌申请数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ApplicationInfo applicationInfo)
    {

        // 获取当前的用户信息,拿到部门id或者角色，过滤权限数据
        SysUser currentUser = ShiroUtils.getSysUser();
        SysDept dept = currentUser.getDept();
        String deptIds="";
        boolean isAdminAndShi=false;

        List<SysRole> roles = currentUser.getRoles();
        HashSet<Long> hset=new HashSet();
        for (SysRole r:roles  ) {
            if (r.getRoleId()==101 || r.getRoleId()==1){//市级-管理员
                deptIds+="";
                isAdminAndShi=true;
            }else if (r.getRoleId()==100){ //区级
                SysDept jdept = deptMapper.selectDeptById(currentUser.getDept().getParentId());
                long qdeptid=jdept.getParentId();
                List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(qdeptid);
                for (SysDept d:sysDepts) {
                    hset.add(d.getDeptId());
                }
                hset.add(qdeptid);
                applicationInfo.setBy8(String.valueOf(currentUser.getUserId()));
            }else if (r.getRoleId()==102){//街道办管理员
                List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(dept.getParentId());
                for (SysDept d:sysDepts) {
                    hset.add(d.getDeptId());
                }
                hset.add(dept.getParentId());
                applicationInfo.setBy8(String.valueOf(currentUser.getUserId()));
            }else if (r.getRoleId()==103){//社区管理员
                deptIds+=(dept.getDeptId()+",");
                hset.add(dept.getDeptId());

                applicationInfo.setBy8(String.valueOf(currentUser.getUserId()));
            }else {  //其他角色查不到数据
                hset.add(999l);
            }
        }

//查询权限范围内 某个社区，超出权限其他社区查不到
        Iterator<Long> iterator = hset.iterator();
        while (iterator.hasNext()){
            deptIds=deptIds+iterator.next()+",";
        }
        if( deptIds.endsWith(","))
            deptIds=deptIds.substring(0,deptIds.length()-1);

        if(null==applicationInfo.getSqCode()){
            if(isAdminAndShi){
                applicationInfo.setSqCode(null);
            }else{
                applicationInfo.setSqCode(String.valueOf(deptIds));
            }
        }else {
            if(!isAdminAndShi){
                String sqcode = applicationInfo.getSqCode();
                if (deptIds.indexOf(sqcode) >= 0) {
                    applicationInfo.setSqCode(sqcode);
                } else {
                    applicationInfo.setSqCode("999");
                }
            }
        }

        if(null!=applicationInfo.getJdbCode()||null !=applicationInfo.getQjCode()||null!=applicationInfo.getSqCode()){
            if(!isAdminAndShi){
                if(null!=applicationInfo.getQjCode()){
                    if(null!=applicationInfo.getJdbCode() && !applicationInfo.getJdbCode().equals("")){
                        if(null!=applicationInfo.getSqCode() && !applicationInfo.getSqCode().equals("")){
                            if(deptIds.indexOf(applicationInfo.getSqCode())<0){
                                applicationInfo.setSqCode("999");
                            }
                        }else{
                            if(deptIds.indexOf(applicationInfo.getJdbCode())<0){
                                applicationInfo.setSqCode("999");
                            }
                        }

                    }else {
                        if (deptIds.indexOf(applicationInfo.getQjCode()) < 0) {
                            applicationInfo.setQjCode("999");
                        }
                    }
                }
            }
        }



        List<ApplicationInfo> list = applicationInfoService.selectApplicationInfoList(applicationInfo);
        applicationInfoService.translation(list);
        ExcelUtil<ApplicationInfo> util = new ExcelUtil<ApplicationInfo>(ApplicationInfo.class);
        return util.exportExcel(list, "lwsq");
    }

    /**
     * 新增离乌申请数据
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存离乌申请数据
     */
    @RequiresPermissions("lwsq:lwsq:add")
    @Log(title = "离乌申请数据", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ApplicationInfo applicationInfo)
    {
        boolean checkResult=applicationInfoService.check(applicationInfo);
        if(checkResult){
            return error("您已提交过申请，请勿重复提交");
        }
        return toAjax(applicationInfoService.insertApplicationInfo(applicationInfo));
    }

    /**
     * 修改离乌申请数据
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        ApplicationInfo applicationInfo = applicationInfoService.selectApplicationInfoById(id);
        mmap.put("applicationInfo", applicationInfo);

        String by9=applicationInfo.getBy9();
        if(by9!=null && by9.indexOf(",")>0) {
            String[] split = by9.split(",");
            List<String> pics = new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                int offset = split[i].indexOf("//");
                pics.add(split[i].substring(offset + 2));
            }
            mmap.put("pics",pics);
        }
        return prefix + "/edit";
    }

    /**
     * 修改保存离乌申请数据
     */
    @RequiresPermissions("lwsq:lwsq:edit")
    @Log(title = "离乌申请数据", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ApplicationInfo applicationInfo)
    {
        return toAjax(applicationInfoService.updateApplicationInfo(applicationInfo));
    }

    /**
     * 删除离乌申请数据
     */
    @RequiresPermissions("lwsq:lwsq:remove")
    @Log(title = "离乌申请数据", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(applicationInfoService.deleteApplicationInfoByIds(ids));
    }


}
